#include "types.h"
#include "riscv.h"
#include "defs.h"
#include "date.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "proc.h"
#include "sysinfo.h"
/*
uint64
sys_login(void) {
  char username[32], password[32];
  // 从用户态读取用户名和密码
  if (argstr(0, username, sizeof(username)) < 0 ||
      argstr(1, password, sizeof(password)) < 0) {
    return -1;
  }
  // 调用验证函数
  return auth_user(username, password);
}*/
int sys_umask(void){
	int new_umask;
	struct proc *p = myproc();
	struct proc *fu = p->parent;
	int old_umask = fu->umask;
	
	if(argint(0,&new_umask) < 0){
		return -1;
	}
	if(new_umask == 0){
		return old_umask;
	}
	fu->umask = new_umask;
	p->umask = new_umask;//zi jin cheng change umask
	return fu->umask;
}

uint64
sys_exit(void)
{
  int n;
  if(argint(0, &n) < 0)
    return -1;
  exit(n);
  return 0;  // not reached
}

uint64
sys_getpid(void)
{
  return myproc()->pid;
}

uint64
sys_fork(void)
{
  return fork();
}

uint64
sys_wait(void)
{
  uint64 p;
  if(argaddr(0, &p) < 0)
    return -1;
  return wait(p);
}

uint64
sys_sbrk(void)
{
  int addr;
  int n;

  if(argint(0, &n) < 0)
    return -1;
  addr = myproc()->sz;
  if(growproc(n) < 0)
    return -1;
  return addr;
}

uint64
sys_sleep(void)
{
  int n;
  uint ticks0;

  if(argint(0, &n) < 0)
    return -1;
  acquire(&tickslock);
  ticks0 = ticks;
  while(ticks - ticks0 < n){
    if(myproc()->killed){
      release(&tickslock);
      return -1;
    }
    sleep(&ticks, &tickslock);
  }
  release(&tickslock);
  return 0;
}

uint64
sys_kill(void)
{
  int pid;

  if(argint(0, &pid) < 0)
    return -1;
  return kill(pid);
}

// return how many clock tick interrupts have occurred
// since start.
uint64
sys_uptime(void)
{
  uint xticks;

  acquire(&tickslock);
  xticks = ticks;
  release(&tickslock);
  return xticks;
}

// trace a system-call
uint64 
sys_trace(void)
{
  int  mask_argument = 0;

  argint(0,&mask_argument); //系统调用传入的第一个参数存入a0寄存器，作为mask
  myproc()->mask |= mask_argument;

  return 0;
}

uint64
sys_info(void)
{
  struct proc *p = myproc();
  uint64 addr;
  struct sysinfo info;

  //get the correct addr
  argaddr(0, &addr);                  

  info.freemem = kfreemem();
  info.freeproc = freeprocnum();

  if (copyout(p->pagetable, addr, (char *)&info, sizeof(info)) < 0) {
    return -1;  // 复制失败，返回错误
  }

  return 0;
}

uint64
sys_ps(void)
{
  print_process_info();
  return 0;
}

uint64
sys_pstree(void)
{
  print_process_tree_interface();
  return 0;
}


